var express = require('express');
var app = require('../app');
var async = require('async');
var fs = require("fs");
var publicIp = require('public-ip');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    var rootDir = app.rootDir;
    // console.log('rootDir ' + rootDir);

    async.parallel({
        oneGetIP: function (callback) {
            publicIp.v4().then(ip => {
                console.log(ip);
                callback(null, ip);
            });
        },
        twoGetMusicList: function (callback) {
            fs.readdir(rootDir + '/public/audio', function (err, files) {
                if (err) {
                    console.log(err);
                    callback(err, null);
                    return;
                }
                var musicList = [];
                // console.log(files);
                files.forEach(function (filename) {
                    // console.log('filename ' + filename);
                    musicList.push('/audio/' + filename);
                });
                console.log(JSON.stringify(musicList));
                callback(null, musicList);
            });
        },
    }, function (error, result) {
        //最后结果
        if (error) {
            console.log('error: ' + error);
            next(error);
            return;
        }
        console.log('result: ' + JSON.stringify(result));
        res.render('index', {
            title: 'Express',
            musicList: JSON.stringify(result.twoGetMusicList),
            ipString: result.oneGetIP
        });
    });
});

module.exports = router;
